package com.wlient.basic.Thread.SysTask;

import java.util.function.IntConsumer;

class FizzBuzz {
    private int n;
    private volatile int index = 1;

    private Object obj = new Object();      //  产生一个对象，对其加锁

    public FizzBuzz(int n) {
        this.n = n;
    }

    // printFizz.run() outputs "fizz".
    public void fizz(Runnable printFizz) throws InterruptedException {
        while (index <= n) {
            synchronized (obj) {
                if (index <= n && index % 3 == 0 && index % 5 != 0) {
                    printFizz.run();
                    index++;
                }
                obj.notifyAll();         //  唤醒所有的线程
            }
        }
    }

    // printBuzz.run() outputs "buzz".
    public void buzz(Runnable printBuzz) throws InterruptedException {
        while (index <= n) {
            synchronized (obj) {
                if (index <= n && index % 5 == 0 && index % 3 != 0) {
                    printBuzz.run();
                    index++;
                }
                obj.notifyAll();
            }
        }
    }

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
        while (index <= n) {
            synchronized (obj) {
                if (index <= n && index % 3 == 0 && index % 5 == 0) {
                    printFizzBuzz.run();
                    index++;
                }
                obj.notifyAll();
            }
        }
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void number(IntConsumer printNumber) throws InterruptedException {
        while (index <= n) {
            synchronized (obj) {
                if (index <= n && index % 3 != 0 && index % 5 != 0) {
                    printNumber.accept(index);
                    index++;
                }
                obj.notifyAll();
            }
        }
    }
}